﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace jsGotoDefinition.VS2010.Helpers
{
    /// <summary>
    /// An object representing a collection of file paths that will be searched in using regular expressions in order to find the defition of a javascript function/method or variable
    /// </summary>
    public class CheckFileCollection : List<string>
    {
        /// <summary>
        /// The current directory where the search starts
        /// </summary>
        public string CurrentDirectory { get; set; }

        /// <summary>
        /// Method that receives a chunk of text and then searches for VS2010 javascript references in the form of 
        /// "reference path= and adds items to the calling object's collection
        /// </summary>
        /// <param name="filetext">The chunk of text containing potential reference tags</param>
        public void AddFromFileText(string filetext) {
            //we need to find all instances of <reference path=""/>
            int startindex = 0;
            int indexof = filetext.IndexOf("<reference path=", startindex);
            while (indexof>=0) {
                string abspath = getAbsolutePath(filetext.Substring(indexof + 17, filetext.IndexOf('"', indexof + 17) - indexof - 17));
                this.Add(abspath);
                startindex = indexof + 17;
                indexof = filetext.IndexOf("<reference path=", startindex);
            }
        }

        /// <summary>
        /// Adds an array of file names to the list
        /// </summary>
        /// <param name="files"></param>
        public void AddFromArray(string[] files) {
            for (int i = 0; i < files.Length; i++) {
                this.Add(files[i]);
            }
        }

        /// <summary>
        /// Private method that returns an absolute path when given a relative path
        /// </summary>
        /// <param name="relpath">The relative path i.e. ../scripts/myscript.js</param>
        /// <returns>Returns an absolute path i.e. c:\myproject\scripts\myscripts.js</returns>
        private string getAbsolutePath(string relpath) {            
            Directory.SetCurrentDirectory(this.CurrentDirectory);
            string retVal = "";
            retVal = System.IO.Path.GetFullPath(relpath);                
            return retVal;
        }
    }
}
